<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="type === '编辑'?$t('编辑'):$t('添加')" :v-if="dialogVisible" :visible.sync="dialogVisible" width="1200px" @close='close' top="5vh">
    <div class="dialogContentBoxMaxHeight90">
      <el-form ref="form" :model="record" label-width="140px" label-position="left" :rules="rules" style="margin:0 20px;">
        <el-form-item :label="$t('BGP协议状态')" prop="status">
          <el-radio-group v-model="record.status" size='small'>
            <el-radio label="on" class="bgpStatusOn">{{$t('开启')}}</el-radio>
            <el-radio label="off" class="bgpStatusOff">{{$t('关闭')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('本地AS号')" prop="asn">
          <el-input v-emoji v-model="record.asn" ref="bgpAsn" :disabled="type === '编辑'?true:false" style="width:280px" size='small'></el-input>
        </el-form-item>
        <el-form-item :label="$t('VRF名称')" prop="vrf">
          <el-input v-emoji v-model="record.vrf" ref="bgpVrf" :disabled="type === '编辑'?true:false" style="width:280px" size='small'></el-input>
        </el-form-item>
        <el-form-item :label="$t('路由器ID')" prop="router_id">
          <template slot="label">{{$t('路由器ID')}}
            <el-tooltip class="item" effect="light" :content="$t('提示信息：路由器ID，默认值0.0.0.0，设置默认值后会将接口地址中最大的地址设置为路由器ID')" placement="top">
              <i class="el-icon-warning-outline" style="color:#666;font-size:14px;"></i>
            </el-tooltip>
          </template>
          <el-input v-emoji v-model="record.router_id" ref="bgpRouterId" style="width:280px" size='small'></el-input>
        </el-form-item>
        <el-form-item :label="$t('导入其他协议的路由')" prop="redistribute">
          <el-checkbox-group v-model="record.redistribute" size='small'>
            <el-checkbox label="connected" class="bgpConnected">{{$t('直连')}}</el-checkbox>
            <el-checkbox label="kernel" class="bgpKernel">{{$t('内核')}}</el-checkbox>
            <el-checkbox label="isis" class="bgpIsis">isis</el-checkbox>
            <el-checkbox label="ospf" class="bgpOspf">ospf</el-checkbox>
            <el-checkbox label="rip" class="bgpRip">rip</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item :label="$t('检查路由的可达性')" prop="import_check">
          <el-radio-group v-model="record.import_check" size='small'>
            <el-radio label="on" class="bgpImportOn">{{$t('开启')}}</el-radio>
            <el-radio label="off" class="bgpImportOff">{{$t('关闭')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('发布路由')" prop="publish_route">
          <div style="border: 1px solid #e6ebf5;padding: 0px 10px 10px;">
            <el-button type="success" size='mini' @click="publishRouteDialogVisible()" class="bgpPublishAddClick">{{$t('添加')}}</el-button>
            <el-table size='mini' ref="publishRouteTable" :data="record.publish_route" tooltip-effect="dark" style="width: 1000px;">
              <el-table-column prop="ip" label="IP" align='center' min-width="100"></el-table-column>
              <el-table-column prop="mask" :label="$t('前缀')" align='center' min-width="100"></el-table-column>
              <el-table-column prop="right" align='center' fixed="right" :label="$t('操作')" width="100">
                <template slot-scope="scope">
                  <el-button type="danger" plain size="mini" @click="publishRouteDeleteData(scope.row, scope.$index)" :class="'publishDel' +(scope.$index+1)">{{$t('删除')}}</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        <el-form-item :label="$t('路由聚合')" prop="aggregated_route">
          <div style="border: 1px solid #e6ebf5;padding: 0px 10px 10px;">
            <el-button type="success" size='mini' @click="aggregatedRouteDialogVisible()" class="bgpAggAddClick">{{$t('添加')}}</el-button>
            <el-table size='mini' ref="aggregatedRouteTable" :data="record.aggregated_route" tooltip-effect="dark" style="width: 1000px;">
              <el-table-column prop="ip" label="IP" align='center' min-width="100"></el-table-column>
              <el-table-column prop="mask" :label="$t('前缀')" align='center' min-width="100"></el-table-column>
              <el-table-column prop="summary_only" :label="$t('仅通告聚合后的路由')" align='center' min-width="100">
                <template slot-scope="scope">
                  {{statusList[scope.row.summary_only]}}
                </template>
              </el-table-column>
              <el-table-column prop="right" align='center' fixed="right" :label="$t('操作')" width="100">
                <template slot-scope="scope">
                  <el-button type="danger" plain size="mini" @click="aggregatedRouteDeleteData(scope.row, scope.$index)" :class="'aggDel' +(scope.$index+1)">{{$t('删除')}}</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        <el-form-item :label="$t('对等体')" prop="peer">
          <div style="border: 1px solid #e6ebf5;padding: 0px 10px 10px;">
            <el-button type="success" size='mini' @click="peerDialogVisible()" class="bgpPeerAddClick">{{$t('添加')}}</el-button>
            <el-table size='mini' ref="peerTable" :data="record.peer" tooltip-effect="dark" style="width: 1000px;">
              <el-table-column prop="peer" label="IP" align='center' min-width="100"></el-table-column>
              <el-table-column prop="remote_as" :label="$t('远程AS号')" align='center' min-width="100"></el-table-column>
              <el-table-column prop="ebgp_multihop" :label="$t('多跳跃点建立连接')" align='center' min-width="100">
                <template slot-scope="scope">
                  {{statusList[scope.row.ebgp_multihop]}}
                </template>
              </el-table-column>
              <el-table-column prop="default_originate" :label="$t('宣告默认路由')" align='center' min-width="100">
                <template slot-scope="scope">
                  {{statusList[scope.row.default_originate]}}
                </template>
              </el-table-column>
              <el-table-column prop="local_as" :label="$t('备用AS号')" align='center' min-width="100"></el-table-column>
              <el-table-column prop="no_prepend" :label="$t('接收到的路由去除备用AS号')" align='center' min-width="100">
                <template slot-scope="scope">
                  {{statusList[scope.row.no_prepend]}}
                </template>
              </el-table-column>
              <el-table-column prop="replace_as" :label="$t('发送出去的路由去除本地AS号')" align='center' min-width="100">
                <template slot-scope="scope">
                  {{statusList[scope.row.replace_as]}}
                </template>
              </el-table-column>
              <el-table-column prop="right" align='center' fixed="right" :label="$t('操作')" width="100">
                <template slot-scope="scope">
                  <el-button type="danger" plain size="mini" @click="peerDeleteData(scope.row, scope.$index)" :class="'peerDel' +(scope.$index+1)">{{$t('删除')}}</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>
      <publish-route-dialog v-if="publishRouteVisible" @addPublishRoute='addPublishRoute' ref="refPublishRouteVisible"></publish-route-dialog>
      <aggregated-route-dialog v-if="aggregatedRouteVisible" @addAggregatedRoute='addAggregatedRoute' ref="refAggregatedRouteVisible"></aggregated-route-dialog>
      <peer-dialog v-if="peerVisible" @addPeer='addPeer' ref="refPeerVisible"></peer-dialog>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="bgpAddSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="bgpAddClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import {
  getBgpInfo, // BGP获取协议信息
  editBgpInfo, // Bgp编辑导入信息
  delBgpAggregatedRoute, // Bgp删除路由聚合
  addBgp, // Bgp添加路由
  delBgpPeer, // Bgp删除对等体
  delBgpPublishRoute // Bgp删除发布路由
} from '@/api/network/route/dynamicRoute/BGP'
import PublishRouteDialog from './bgpComponents/PublishRouteDialog'
import AggregatedRouteDialog from './bgpComponents/AggregatedRouteDialog'
import PeerDialog from './bgpComponents/PeerDialog'
import { inputClass } from '@/utils/input-class.js'
export default {
  name: 'BgpDialog',
  components: {
    PublishRouteDialog,
    AggregatedRouteDialog,
    PeerDialog
  },
  data () {
    var validateASN = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else if (!this.isInteger(value)) {
        callback(new Error(this.$t('只能输入整数')))
      } else if (Number(value) > 4294967295 || Number(value) < 1) {
        callback(new Error(this.$t('请输入1-4294967295之间的数字')))
      } else {
        callback()
      }
    }
    var validateVrf = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else if (String(value).length > 15) {
        callback(new Error(this.$t('长度不能超过15个字符')))
      } else {
        callback()
      }
    }
    var validateIp = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback()
      } else if (this.isValidIP(value)) {
        callback()
      } else {
        callback(new Error(this.$t('请输入正确的IPv4地址')))
      }
    }

    return {
      dialogVisible: false,
      publishRouteVisible: false, // 发布路由
      aggregatedRouteVisible: false, // 路由聚合
      peerVisible: false, // 路由聚合
      record: {
        id: '',
        asn: '',
        vrf: 'default',
        router_id: '0.0.0.0',
        status: 'off',
        redistribute: [],
        import_check: 'off',
        publish_route: [],
        aggregated_route: [],
        peer: []
      },
      recordCopy: {
        id: '',
        asn: '',
        vrf: 'default',
        router_id: '0.0.0.0',
        status: 'off',
        redistribute: [],
        import_check: 'off',
        publish_route: [],
        aggregated_route: [],
        peer: []
      },
      type: '',
      statusList: {
        'off': this.$t('关闭'),
        'on': this.$t('开启')
      },
      rules: {
        asn: [{ required: false, validator: validateASN, trigger: 'blur' }],
        vrf: [{ required: false, validator: validateVrf, trigger: 'blur' }],
        router_id: [{ required: false, validator: validateIp, trigger: 'blur' }]
      }
    }
  },
  methods: {
    init (data, type) {
      this.dialogVisible = true
      this.type = type
      if (data) {
        this.record.id = data.id
        this.record.asn = data.asn
        this.record.vrf = data.vrf
        this.record.router_id = data.router_id
        this.record.status = data.status
        this.record.redistribute = data.redistribute ? data.redistribute.split(',') : []
        this.record.import_check = data.import_check
        this.record.publish_route = data.network[0]
        this.record.aggregated_route = data.ggregate_address[0]
        this.record.peer = data.neighbor[0]
      }
      this.$nextTick(() => {
        const data = ['bgpAsn', 'bgpVrf', 'bgpRouterId']
        inputClass(this.$refs, data)
      })
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.type === '编辑') {
            let formData = JSON.parse(JSON.stringify(this.record))
            formData.publish_route = JSON.stringify(formData.publish_route)
            formData.aggregated_route = JSON.stringify(formData.aggregated_route)
            formData.peer = JSON.stringify(formData.peer)
            editBgpInfo(formData).then(res => {
              if (res.status === 0) {
                this.$messages.success(this.$t('执行成功'))
                this.close()
                this.$parent.listData()
              }
            })
          } else {
            let formData = JSON.parse(JSON.stringify(this.record))
            formData.publish_route = JSON.stringify(formData.publish_route)
            formData.aggregated_route = JSON.stringify(formData.aggregated_route)
            formData.peer = JSON.stringify(formData.peer)
            addBgp(formData).then(res => {
              if (res.status === 0) {
                this.$messages.success(this.$t('执行成功'))
                this.close()
                this.$parent.listData()
              }
            })
          }
        }
      })
    },
    close () {
      this.type = ''
      this.dialogVisible = false
      this.record = Object.assign({}, this.recordCopy)
      this.$refs.form.resetFields()
      this.ifnameList = []
      this.isisList = []
    },
    listData () {
      getBgpInfo({ id: this.record.id }).then(res => {
        if (res.status === 0) {
          this.record.publish_route = res.info[0].network[0]
          this.record.aggregated_route = res.info[0].ggregate_address[0]
          this.record.peer = res.info[0].neighbor[0]
        }
      })
      this.$emit('listData')
    },
    isInteger (value) {
      return (!isNaN(value) && (parseInt(value).toString().length === String(Number(value)).length))
    },
    publishRouteDialogVisible () {
      this.publishRouteVisible = true
      this.$nextTick(() => {
        this.$refs.refPublishRouteVisible.init(this.type, this.record.id)
      })
    },
    publishRouteDeleteData (row, index) {
      if (this.type === '编辑') {
        let formData = JSON.parse(JSON.stringify(row))
        formData.id = this.record.id
        delBgpPublishRoute(formData).then(res => {
          if (res.status === 0) {
            this.$messages.success(this.$t('删除成功'))
            this.listData()
          }
        })
      } else {
        this.record.publish_route.splice(index, 1)
      }
    },
    addPublishRoute (data) {
      if (this.type === '编辑') {
        this.listData()
      } else {
        this.record.publish_route.push(data)
      }
    },
    aggregatedRouteDialogVisible () {
      this.aggregatedRouteVisible = true
      this.$nextTick(() => {
        this.$refs.refAggregatedRouteVisible.init(this.type, this.record.id)
      })
    },
    aggregatedRouteDeleteData (row, index) {
      if (this.type === '编辑') {
        let formData = JSON.parse(JSON.stringify(row))
        formData.id = this.record.id
        delBgpAggregatedRoute(formData).then(res => {
          if (res.status === 0) {
            this.$messages.success(this.$t('删除成功'))
            this.listData()
          }
        })
      } else {
        this.record.aggregated_route.splice(index, 1)
      }
    },
    addAggregatedRoute (data) {
      if (this.type === '编辑') {
        this.listData()
      } else {
        this.record.aggregated_route.push(data)
      }
    },
    peerDialogVisible () {
      this.peerVisible = true
      this.$nextTick(() => {
        this.$refs.refPeerVisible.init(this.type, this.record.id)
      })
    },
    peerDeleteData (row, index) {
      if (this.type === '编辑') {
        let formData = JSON.parse(JSON.stringify(row))
        formData.id = this.record.id
        delBgpPeer(formData).then(res => {
          if (res.status === 0) {
            this.$messages.success(this.$t('删除成功'))
            this.listData()
          }
        })
      } else {
        this.record.peer.splice(index, 1)
      }
    },
    addPeer (data) {
      if (this.type === '编辑') {
        this.listData()
      } else {
        this.record.peer.push(data)
      }
    },
    isValidIP (ip) {
      let reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
      return reg.test(ip)
    }
  }
}
</script>
